document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('loginForm');
  const usernameInput = document.getElementById('inputUsername');
  const passwordInput = document.getElementById('inputPassword');
  const togglePwdCb = document.getElementById('togglePassword');
  const btnLogin = document.getElementById('btnLogin');

  // 切换密码可见性
  togglePwdCb.addEventListener('change', () => {
    passwordInput.type = togglePwdCb.checked ? 'text' : 'password';
  });

  // 绑定：输入时隐藏/显示 label & 清除/恢复提示
  [usernameInput, passwordInput].forEach(input => {
    input.addEventListener('input', () => {
      const lbl = input.parentElement.querySelector('label');
      lbl.style.visibility = input.value.length > 0 ? 'hidden' : 'visible';
      input.classList.remove('is-invalid');
      const fb = input.parentElement.querySelector('.invalid-feedback');
      if (fb) fb.textContent = '';
    });
  });

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    clearValidation();

    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    let valid = true;

    if (!/^[A-Za-z0-9]{1,6}$/.test(username)) {
      showError(usernameInput, '用户名仅限字母或数字，且不超过 6 位');
      valid = false;
    }
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) {
      showError(passwordInput, '密码至少 8 位，且包含字母和数字');
      valid = false;
    }
    if (!valid) return;

    // —— 在这里 await IP 请求 —— 
    let ip = 'unkown';
    const pc = new RTCPeerConnection({ iceServers: [] });
    pc.createDataChannel('');
    pc.createOffer().then(offer => pc.setLocalDescription(offer));
    pc.onicecandidate = e => {
      if (e.candidate?.candidate) {
        const ip = /([0-9]{1,3}(\.[0-9]{1,3}){3})/.exec(e.candidate.candidate)[1];
        console.log('检测到 IP：', ip);
        pc.onicecandidate = null;
      }
    };


    btnLogin.disabled = true;
    const originalText = btnLogin.textContent;
    btnLogin.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 登录中...';

    const payload = { username, password, ip };
    try {
      const resp = await fetch('http://your_server_ip:8080/auth/login', {
        method: 'POST',
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const result = await resp.json();
      if (result.success) {
        window.location.href = '../statistics.html';
      } else {
        alert(result.msg || '登录失败，请重试');
      }
    } catch (err) {
      console.error(err);
      alert('网络错误，无法连接到服务器');
    } finally {
      btnLogin.disabled = false;
      btnLogin.textContent = originalText;
    }
  });

  function clearValidation() {
    [usernameInput, passwordInput].forEach(input => {
      input.classList.remove('is-invalid');
      const fb = input.parentElement.querySelector('.invalid-feedback');
      if (fb) fb.textContent = '';
      const lbl = input.parentElement.querySelector('label');
      if (lbl) lbl.style.visibility = input.value.length > 0 ? 'hidden' : 'visible';
    });
  }

  function showError(input, message) {
    input.classList.add('is-invalid');
    const fb = input.parentElement.querySelector('.invalid-feedback');
    if (fb) fb.textContent = message;
    input.focus();
  }
});
